有些欄位會一起出現在不同的class與參數列表.
當一個系統的各處程式碼常出現這些欄位且形影不離, 勢必得思考他們與類別或參數列表的關聯性.
如果缺少其中一位的賦值, 是不是得檢查所有程式碼哪裡也有這種狀況?
假設一個校務系統, 課程需要老師的Id和名字, 而班級也需要老師的Id和名字,
此時會有這兩個class:
Course course = new Course
{
CourseId = "CS520",
CourseName = "Introduction to Computer Science",
TeacherId = "C580001",
TeacherName = "BillyWang"
};
Class myClass = new Class
{
ClassId = 11301,
TeacherId = "C580001",
TeacherName = "BillyWang"
};
由於老師的Id與Name, 都是一起出現, 因此可以抽出一個Teacher類別, 將Id與Name都放在此類別:
Course course = new Course
{
CourseId = "CS520",
CourseName = "Introduction to Computer Science",
Teacher = new Teacher{ Id = "C580001", Name = "BillyWang" }
};
Class myClass = new Class
{
ClassId = 11301,
Teacher = new Teacher{ Id = "C580001", Name = "BillyWang" }
};
經過這種重構, 我們可以為Teacher增加一些行為(函數), 讓系統各處的Teacher資料處理方式一致.
回想.NET最常見的應用: Window Form元件, 其中座標Point是個明顯的案例, 一組座標(X,Y)必須一起出現,
所以包裝成Point類別是良好的設計.